package org.qiancizhan.Mapper;

import org.qiancizhan.Config.MySQL;
import org.qiancizhan.Model.DTO.PageConfigDTO;
import org.qiancizhan.Model.POJO.UserPOJO;
import org.qiancizhan.Model.POJO.WordPOJO;
import org.qiancizhan.Utils.ThreadLocalUtil;

import java.util.List;

public class CollectionMapper {
    private final MySQL mySQL = MySQL.getInstance();

    public boolean addCollection(WordPOJO word) {
        UserPOJO map = ThreadLocalUtil.get();
        try {
            return mySQL.executeUpdate("INSERT INTO collection_word (fk_users_id, word, translate) VALUES (?, ?, ?)", map.getId(), word.getWord(), word.getTranslate()) > 0;
        } catch (Exception e) {
            return false;
        }
    }

    public List<WordPOJO> getUserCollectionWords(PageConfigDTO pageConfigDTO) {
        UserPOJO map = ThreadLocalUtil.get();
        int pageSize = pageConfigDTO.getPageSize();
        int currentNum = pageConfigDTO.getCurrentNum();
        int offset = (currentNum - 1) * pageSize;
        String sql = String.format("SELECT id,word,translate FROM `collection_word` WHERE collection_word.fk_users_id = %d LIMIT %d OFFSET %d", map.getId(), pageSize, offset);
        return mySQL.executeQuery(sql, rs -> {
            WordPOJO wordPOJO = new WordPOJO();
            wordPOJO.setId(rs.getInt("id"));
            wordPOJO.setWord(rs.getString("word"));
            wordPOJO.setTranslate(rs.getString("translate"));
            return wordPOJO;
        });
    }

    public int getUserWord_count() {
        UserPOJO map = ThreadLocalUtil.get();
        String sql = String.format("SELECT * FROM `collection_word` WHERE collection_word.fk_users_id = %d", map.getId());
        return mySQL.executeQuery(sql, rs -> {
            WordPOJO wordPOJO = new WordPOJO();
            wordPOJO.setId(rs.getInt("id"));
            wordPOJO.setWord(rs.getString("word"));
            wordPOJO.setTranslate(rs.getString("translate"));
            return wordPOJO;
        }).size();

    }

    public boolean delCollection(int collectionId) {
        return mySQL.executeUpdate("DELETE FROM `collection_word` WHERE id = ?", collectionId) > 0;
    }

    public boolean clearCollection() {
        UserPOJO map = ThreadLocalUtil.get();
        return mySQL.executeUpdate("DELETE FROM `collection_word` WHERE fk_users_id = ?", map.getId()) > 0;
    }
}
